﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _03工厂方法设计模式.工厂方法反射
{
    public class ReflectionFactory
    {
        //根据用户输入的操作符 返回一个对象
        Dictionary<string, ICalFactory> dic=new Dictionary<string, ICalFactory>();
        public ReflectionFactory()
        {
            //拿到当前正在运行的程序集
            Assembly assembly= Assembly.GetExecutingAssembly();
            foreach (var item in assembly.GetTypes())
            {
                //IsAssignableFrom 表示item继承了ICalFactory或实现了ICalFactory
                if (typeof(ICalFactory).IsAssignableFrom(item)&&!item.IsInterface)
                {
                    OperFactory of= item.GetCustomAttribute<OperFactory>();
                    if (of != null)
                    {
                        //给键值对集合赋值
                        dic[of.Oper] = Activator.CreateInstance(item) as ICalFactory;
                    }
                }
            }
        }

        public ICalFactory GetFac(string s)
        {
            if (dic.ContainsKey(s))
            {
                return dic[s];
            }
            return null;
        }
    }
}
